﻿using System;

namespace CarEvent
{
    public class Car
    {
        // 申明委托
        public delegate void CarEngineHandler(string msg);

        // 创建委托实例Exploded和AboutToBlow事件
        public event CarEngineHandler Exploded;
        public event CarEngineHandler AboutToBlow;

        // 设置属性
        public int CurrentSpeed { get; set; }
        public int MaxSpeed { get; set; }
        public string PetName { get; set; }

        // 用于判断是否超速
        public bool CarIsDead;

        // 构造函数
        public Car()
        {
            MaxSpeed = 100;
        }

        // 构造函数重载
        public Car(string name, int maxSp, int currSp)
        {
            PetName = name;
            MaxSpeed = maxSp;
            CurrentSpeed = currSp;
        }

        // 用于触发Exploded和AboutToBlow事件
        public void Accelerate(int delta)
        {
            // “踩油门”加速
            CurrentSpeed += delta;

            // 判断时速
            if (CurrentSpeed >= MaxSpeed)
            {
                CarIsDead = true;
            }
            else
            {
                CarIsDead = false;
            }

            // 如果Car超速了，触发Exploded使劲按
            if (CarIsDead)
            {
                // 判断是否被委托联系起来
                if (Exploded != null)
                {
                    // 调用CarDead事件
                    Exploded("sorry, this car is dead");
                }
            }
            else
            {
                // 如果没有超速，则提示快要超速并显示实时车速
                if ((MaxSpeed - CurrentSpeed) > 0 && (MaxSpeed - CurrentSpeed) <= 10 && AboutToBlow != null) // 判断是否被委托联系起来且速度是否接近临界值
                {
                    // 调用NearDead事件
                    AboutToBlow("careful buddy ! gonna blow !");
                    // 显示实时车速
                    Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed);
                }
            }
        }
    }

    // 订阅类书写举例
    public class Answer
    {
        // 汽车已爆缸事件
        public void CarDead(string msg)
        {
            Console.WriteLine("sorry, this car is dead");
        }

        // 汽车快要爆缸事件
        public void NearDead(string msg)
        {
            Console.WriteLine("careful buddy ! gonna blow !");
        }
    }

    // 主函数书写
    public class Test
    {
        static void Main(string[] args)
        {
            // 创建实例并初始化，初始速度为93
            Car c = new Car("奔驰",100,93);
            Answer an = new Answer();
            // Exploded"绑定"CarDead
            c.Exploded += new Car.CarEngineHandler(an.CarDead);
            // AboutToBlow"绑定"NearDead
            c.AboutToBlow += new Car.CarEngineHandler(an.NearDead);
            // 第一次加速，时速小于100，引发得事件为“快要爆缸”并显示实时车速为99
            c.Accelerate(6);
            // 等待回车键已启动第二次加速
            Console.ReadLine();
            // 第二次加速，时速超过100，引发事件为“已爆缸”，不显示车速
            c.Accelerate(2);

            Console.ReadKey();
        }
    }
}